//
//  SplashViewController.m
//  NewApp
//
//  Created by 健 吕 on 12-6-9.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SplashViewController.h"
#import "RequestEngine.h"

@interface SplashViewController (Privates)

- (void) requestDidUpdate:(RequestEngine *) engine 
               withObject:(id) object;

@end

@implementation SplashViewController

@synthesize delegate;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imageView.image = [UIImage imageNamed:@"splash.png"];
    [self.view addSubview:imageView];
    [imageView release];
    
    _activityIndicator  = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activityIndicator.frame = CGRectMake(140.f, 300.f, 40.f, 40.f);
    [self.view addSubview:_activityIndicator];
    
    [_activityIndicator startAnimating];

}

- (void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    currentEngine = [[RequestEngine alloc] initWithTarget:self 
                                            action:@selector(requestDidUpdate:withObject:)];
    [currentEngine shakeHandWithServer];
}

- (void) dealloc {
    if (currentEngine != nil) {
        currentEngine.delegate = nil;
        [currentEngine release];
    }
    
    [_activityIndicator release];
    
    [super dealloc];
}


#pragma mark -
#pragma mark - Private methods

- (void) requestDidUpdate:(RequestEngine *) engine 
               withObject:(id) object {
    
    [_activityIndicator stopAnimating];
    
    if ([object isKindOfClass:[NSDictionary class]]) {
        if (nil != self.delegate) {
            if ([self.delegate respondsToSelector:@selector(splashDidLoadCompleted)]) {
                [self.delegate splashDidLoadCompleted];
            }
        }
    }else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" 
                                                        message:@"无法连接到服务器，請開啟3G上網，或是連線wifi" 
                                                       delegate:nil 
                                              cancelButtonTitle:@"知道了" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    
    [currentEngine release];
    currentEngine = nil;
}
@end
